import logging
import os
from logging.handlers import TimedRotatingFileHandler
from datetime import  datetime



class CustomTimedRotatingFileHandler(TimedRotatingFileHandler):
    def __init__(self, filename, *args, **kwargs):
        # 替换文件名为当前日期
        current_date = datetime.now().strftime("%Y-%m-%d")
        new_filename = filename.replace("%Y-%m-%d", current_date)
        super().__init__(new_filename, *args, **kwargs)

    def close(self):
        # 确保关闭文件描述符
        if self.stream:
            self.stream.close()
            self.stream = None
        super().close()

logger = logging.getLogger("uvicorn")

# 使用示例
log_dir = "./logs"
os.makedirs(log_dir, exist_ok=True)

handler = CustomTimedRotatingFileHandler(
    filename="./logs/app-%Y-%m-%d.log",
    when="midnight",
    backupCount=10,
    encoding="utf-8",
)